package com.googlecode.flealancemarket.service.facades.impl;

import com.googlecode.flealancemarket.metamodel.Category;
import com.googlecode.flealancemarket.metamodel.CategoryGroup;
import com.googlecode.flealancemarket.metamodel.Job;
import com.googlecode.flealancemarket.service.facades.CategoriesFacade;
import java.util.List;
import java.util.Set;
import org.hibernate.FetchMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Transactional;

public class CategoriesFacadeImpl extends HibernateDaoSupport implements CategoriesFacade {

    @Transactional
    public List<CategoryGroup> getCategories() {
        Query q = getSessionFactory().getCurrentSession().createQuery("from CategoryGroupBean");
        return q.list();
    }

    @Transactional
    public Category getCategory(long categoryId) {
        Session s = getSessionFactory().getCurrentSession();
        Category c = (Category)s
                                .createCriteria(Category.class)
                                .add(Restrictions.eq("_id", categoryId))
                                .uniqueResult();
        if(c==null)
            return null;

        List<Job> list = s
                            .createCriteria(Job.class)
                            .add(Restrictions.eq("category", c))
                            .list();
        c.setJobs(list);
        return c;
    }
    
    @Transactional
    public CategoryGroup saveCategoryGroup(CategoryGroup cg){
        Session s = getSessionFactory().getCurrentSession();
        s.saveOrUpdate(cg);
        return cg;
    }

    @Transactional
    public Category saveCategoryWithoutGroup(Category ctg) {
        Session s = getSessionFactory().getCurrentSession();
        s.saveOrUpdate(ctg);
        ctg.setCategoryGroup(null);
        return ctg;
    }
}
